package tuhao.hibernate.www.util.controller;


import com.tuhao.www.common.JsonResult;
import org.apache.log4j.Logger;

/**
 * 作用：作为controller控制层的父类，一些通用的处理，放入该父类处理
 * 比如：获取request中的对象，在对前台返回json的封装
 */
public abstract class TokenController {
	private static Logger log = Logger.getLogger(TokenController.class);

	/*@Autowired
	public MessageSource messageSource;

	private static final String TOKEN_KEY = "_synchronizerToken";

	*//**
	 * @return
	 *//*
	public static String getTokenKey() {
		return TOKEN_KEY;
	}

	*//**
	 * 保存token信息
	 *//*
	protected void saveToken(HttpServletRequest request) {
		request.getSession().setAttribute(TOKEN_KEY, nextToken());
	}

	*//**
	 * 保存token信息,并返回token值
	 *//*
	protected String saveAndGetToken(HttpServletRequest request) {
		String token = nextToken();
		request.getSession().setAttribute(TOKEN_KEY, token);
		return token;
	}

	*//**
	 * 校验session中的token值和reqeust中的是否一致
	 * 
	 * @param request
	 * @return
	 *//*
	protected boolean isTokenValid(HttpServletRequest request) {
		String requestToken = request.getParameter(TOKEN_KEY);

		String sessionToken = (String) request.getSession().getAttribute(TOKEN_KEY);

		if (sessionToken == null || !sessionToken.equals(requestToken)) {
			return false;
		}

		// 保存下一个token
		saveToken(request);

		return true;
	}

	protected boolean isTokenValid(HttpServletRequest request, String requestToken) {

		String sessionToken = (String) request.getSession().getAttribute(TOKEN_KEY);

		if (sessionToken == null || !sessionToken.equals(requestToken)) {
			return false;
		}

		// 保存下一个token
		saveToken(request);

		return true;
	}

	public static String nextToken() {
		long seed = System.currentTimeMillis();
		Random r = new Random();
		r.setSeed(seed);
		return Long.toString(seed) + Long.toString(Math.abs(r.nextLong()));
	}

	*//**
	 * 设置视图提示消息
	 * 
	 * @param mv
	 * @param messageCode
	 *//*
	public void setMessage(ModelAndView mv, String messageCode) {
		mv.addObject("message", messageSource.getMessage(messageCode, null, null));
	}

	*//**
	 * 获取国际化提示消息/错误消息
	 * 
	 *//*
	public String getMAndE(String messageCode) {
		return messageSource.getMessage(messageCode, null, null);
	}

	*//**
	 * 设置视图错误消息
	 * 
	 * @param mv
	 * @param errorCode
	 *//*
	public void setError(ModelAndView mv, String errorCode) {
		mv.addObject("error", messageSource.getMessage(errorCode, null, null));
	}

	*//**
	 * 检查表单提交的
	 * 
	 * @param name
	 * @return
	 *//*
	protected String checkToken(String name, int resultType, HttpServletRequest request) {
		String paramValue = paramString(name, request);
		String tokenValue = StringUtil.isNull((String) request.getSession().getAttribute(name));
		String msg = "";
		// 参数、session中都没用token值提示错误
		if (paramValue.isEmpty() && tokenValue.isEmpty()) {
			msg = "会话Token未设定，请刷新标详情页后重试。";
		} else if (paramValue.isEmpty() && !tokenValue.isEmpty()) {
			msg = "表单Token未设定，请刷新标详情页后重试。";
		} else if (paramValue.equals(tokenValue) && !tokenValue.isEmpty()) { // session中有token,防止重复提交检查
			request.getSession().removeAttribute(name);
		} else {
			msg = "请勿重复提交。";
		}
		return msg;
	}

	protected String paramString(String str, HttpServletRequest request) {
		return StringUtil.isNull(request.getParameter(str));
	}

	protected User getSessionUser(HttpSession session) {
		return (User) session.getAttribute(Constant.SESSION_USER);
	}

	protected void setSessionUser(HttpSession session, User user) {
		session.setAttribute(Constant.SESSION_USER, user);
	}

	*//**
	 * 
	 *            为0，则是清除cookie
	 *//*
	protected void setCookie(HttpServletResponse response, String cookieName, String cookieValue, int maxAge) {
		Cookie error = new Cookie(cookieName, cookieValue);
		error.setMaxAge(maxAge);
		response.addCookie(error);
	}

	*//*
	 * 获取Session中的用户认证信息
	 * 
	 * @return
	 *//*
//	protected UserIdentify getSessionUserIdentify(HttpSession session) {
//		UserIdentify userIdentify = (UserIdentify) session.getAttribute(Constant.SESSION_USER_IDENTIFY);
//		return userIdentify;
//	}
*/
	public void success(JsonResult json) {
		json.setStatus(200);
		json.setFlag(1);
	}

	public void success(JsonResult json, Object data) {
		json.setStatus(200);
		json.setData(data);
		json.setFlag(1);
	}

	public void success(JsonResult json, Object data, String msg) {
		json.setStatus(200);
		json.setData(data);
		json.setMsg(msg);
		json.setFlag(1);
	}

	public void error(JsonResult json, String msg) {
		json.setStatus(500);
		json.setMsg(msg);
		json.setFlag(0);
	}

	public void nosignin(JsonResult json) {
		json.setStatus(401);
		json.setFlag(2);
	}

	public void notfind(JsonResult json) {
		json.setStatus(404);
		json.setMsg("对不起，找不到您访问的资源");
		json.setFlag(3);
	}
/*
	public void redirect(String url, HttpServletResponse response) {
		try {
			response.sendRedirect(url);
		} catch (IOException e) {
			//throw new BussinessException("重定向错误");
		}
	}
	
	public void redirectWhere(String url, HttpServletResponse response) {
		try {
			response.sendRedirect(url);
		} catch (IOException e) {
			//throw new BussinessException("重定向错误");
		}
	}
	
	public String getIpRequest(HttpServletRequest request) {
		String ip = request.getHeader("X-Forwarded-For");
		if(StringUtil.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)){
			int index = ip.indexOf(",");
			if(index != -1){
				return ip.substring(0,index);
			}else{
				return ip;
			}
		}
		ip = request.getHeader("X-Real-IP");
		if(StringUtil.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)){
			return ip;
		}
		return request.getRemoteAddr();
	}

	*//**
	 * 获取参数信息
	 * @param aoData
	 * @return
	 *//*
	public Map<String, Object> getParams(String aoData){
		JSONArray jsonarray = JSONArray.fromObject(aoData);
        //这里获取从前台传递过来的参数，从而确保是否分页、是否进行查询、是否排序等
		Map<String,Object> aoDataMap = new LinkedHashMap<>();
		Map<String,Object> result = new LinkedHashMap<String, Object>();
		result.put("currentPage",0);
		result.put("pernum",PageInfo.ROWS);
        for (int i = 0; i < jsonarray.size(); i++) {
            JSONObject obj = (JSONObject) jsonarray.get(i);
			aoDataMap.put(obj.get("name").toString(), obj.get("value"));
        }
		if (aoDataMap == null) return result;
		//记录操作的次数
		String sEcho = aoDataMap.get("sEcho").toString();
		// 查询页数，即当前页数
		int currentPage = 0;
		// 每页显示的行数
		int pernum = PageInfo.ROWS;
		try {
			currentPage = Integer.valueOf(aoDataMap.get("iDisplayStart").toString());
			pernum = Integer.valueOf(aoDataMap.get("iDisplayLength").toString());
		} catch (Exception e) {
			log.error("获得分页参数失败");
		}

		//搜索条件为佣金等级或称号
		String serchName = String.valueOf(aoDataMap.get("searchName"));
		result.put("searchName", serchName);
		result.put("currentPage",currentPage);
		result.put("pernum",pernum);
		return result;
	}

	*//**
	 * 生成分页信息
	 * @return
	 *//*
	public Map<String, Object> generatorPage(String sEcho, Page page){
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("draw", sEcho);
		result.put("recordsTotal", page.getTotalPages());
		result.put("recordsFiltered", page.getTotalPages());
		result.put("data", page.getContent());
		return result;
	}

	*//**
	 * 生成分页信息
	 * @return
	 *//*
	public Map<String, Object> generatorPage(String sEcho, PageDataList pageDataList){
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("draw", sEcho);
		result.put("recordsTotal", pageDataList.getPage().getTotal());
		result.put("recordsFiltered", pageDataList.getPage().getCurrentPage());
		result.put("data", pageDataList.getList());
		return result;
	}*/

}
